package com.h3c.nem.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.h3c.nem.cache.TbOfferWorkerCache;
import com.h3c.nem.config.SpringUtil;
import com.h3c.nem.dto.TbWorkerExperienceDTO;
import com.h3c.nem.entity.TbOfferStudy;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.entity.TbWorkerExperience;
import com.h3c.nem.mapper.TbOfferStudyMapper;
import com.h3c.nem.mapper.TbWorkerExperienceMapper;
import com.h3c.nem.mapstruct.TbWorkerExperienceMapstruct;
import com.h3c.nem.service.ITbOfferWorkerService;
import com.h3c.nem.service.ITbWorkerExperienceService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.vo.TbWorkerExperienceVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 实现类
 *
 * @author chenyifan
 * @since 2022-06-06 15:46:13
 */
@Service
public class TbWorkerExperienceServiceImpl extends ServiceImpl<TbWorkerExperienceMapper, TbWorkerExperience> implements ITbWorkerExperienceService {

    @Resource
    private TbOfferStudyMapper studyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWorkExperience(List<TbWorkerExperienceDTO> workerExperienceDTOS) {
        TbOfferWorker offerWorker = SpringUtil.getBean(ITbOfferWorkerService.class).getById(CommonUtil.getActivUser().getUserId());
        remove(new QueryWrapper<TbWorkerExperience>().lambda()
                .eq(TbWorkerExperience::getWorkerId, CommonUtil.getActivUser().getUserId())
        );
        LambdaQueryWrapper<TbOfferStudy> studyWrapper = new LambdaQueryWrapper<>();
        studyWrapper.eq(TbOfferStudy::getWorkerId, offerWorker.getWorkerId()).orderByAsc(TbOfferStudy::getEndDate).last("limit 1");
        TbOfferStudy study = studyMapper.selectOne(studyWrapper);
        List<TbWorkerExperience> workerExperiences = TbWorkerExperienceMapstruct.INSTANCE.DTOList2EntityList(workerExperienceDTOS);
        for (TbWorkerExperience workerExperience : workerExperiences) {
            if (workerExperience.getExperienceType().equals(1) && Objects.isNull(workerExperience.getEndDate())) {
                workerExperience.setEndDate(offerWorker.getLastLeaveDate());
            }
            if (Objects.nonNull(workerExperience.getEndDate()) && DateUtil.compare(workerExperience.getBeginDate(), workerExperience.getEndDate(), null) > 0) {
                throw new AppBusinessException("工作单位为:" + workerExperience.getWorkPlace() + "的工作经历开始日期必须早于结束日期");
            }
            if (study != null && Objects.nonNull(study.getEndDate()) && Objects.nonNull(workerExperience.getBeginDate()) && DateUtil.compare(study.getEndDate(), workerExperience.getBeginDate()) > 0) {
                throw new AppBusinessException("工作单位为:" + workerExperience.getWorkPlace() + "的工作经历开始日期早于您第一份学历的毕业日期，请您正确填写您的工作经历（不用包含实习经历），谢谢！" );
            }
        }
        //根据经历开始时间排序
        workerExperiences.sort(Comparator.comparing(TbWorkerExperience::getBeginDate));
        //判断前后是否有相差6个月的工作经历
        workerExperiences.sort((o2, o1) -> {
//            if (DateUtil.compare(o2.getBeginDate(), o1.getEndDate()) <= 0) {
//                throw new AppBusinessException("您输入的工作经历开始日期必须大于上一份的结束日期，请调整！");
//            }
            if (DateUtil.compare(o1.getEndDate(), DateUtil.offset(o2.getBeginDate(), DateField.MONTH, -6)) <= 0) {
                throw new AppBusinessException("您维护的工作经历中存在超过6个月的空档期，请维护这个时段内的非工作经历，谢谢");
            }
            return 0;
        });
        workerExperiences.sort(Comparator.comparing(TbWorkerExperience::getBeginDate));
        workerExperiences.forEach(s -> s.setExperienceId(IdWorker.nextId() + "")
                .setWorkerId(CommonUtil.getActivUser().getUserId())
                .setUpdateTime(new Date()));
        saveBatch(workerExperiences);
        TbOfferWorkerCache.updateFillStatus(CommonUtil.getActivUser().getUserId(), TbOfferWorkerCache.WORKER_EXPERIENCE);
    }

    @Override
    public List<TbWorkerExperienceVO> showWorkExperience() {
        List<TbWorkerExperience> experiences = list(new QueryWrapper<TbWorkerExperience>().lambda()
                .eq(TbWorkerExperience::getWorkerId, CommonUtil.getActivUser().getUserId())
        );
        return TbWorkerExperienceMapstruct.INSTANCE.entityList2VOList(experiences);
    }

    @Override
    public List<TbWorkerExperienceVO> getWorkExperienceByWorkerId(String workerId) {
        LambdaQueryWrapper<TbWorkerExperience> queryWrapper = new QueryWrapper<TbWorkerExperience>().lambda();
        queryWrapper.eq(TbWorkerExperience::getWorkerId, workerId);
        List<TbWorkerExperience> experiences = list(queryWrapper);
        return TbWorkerExperienceMapstruct.INSTANCE.entityList2VOList(experiences);
    }

    /**
     * 把离职日期设到工作经历结束日期为空的记录上
     */
    public void setWorkExpWithoutEnd(Date leaveDate, String workerId) {
        if (leaveDate != null && !StringUtils.isEmpty(workerId)) {
            lambdaUpdate().set(TbWorkerExperience::getEndDate, leaveDate).eq(TbWorkerExperience::getWorkerId, workerId).isNull(TbWorkerExperience::getEndDate).update();
        }
    }

    public Boolean checkJoinDateAndEndDate(String workerId, Date joinDate) {
        if (StringUtils.hasText(workerId)) {
            if (joinDate != null) {
                TbWorkerExperience exp = lambdaQuery().eq(TbWorkerExperience::getWorkerId, workerId)
                        .orderByDesc(TbWorkerExperience::getEndDate)
                        .last("limit 1").one();
                if (exp != null) {
                    if (exp.getEndDate() != null) {
                        return joinDate.compareTo(exp.getEndDate()) >= 0;
                    } else {
                        return true;
                    }
                } else {
                    return true;
                }
            } else {
                throw new AppBusinessException("您还没有计划入职日期");
            }
        } else {
            return false;
        }
    }

}

